package com.lance.answer.question_export;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;

/**
 * <p>以老师的身份获取答案<p>
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class GetAnswerByTeacher2 {

    public static void login(WebDriver driver, String userName, String pwd) {
        WebElement agreeButton = driver.findElement(By.id("RememberLogin"));
        agreeButton.click();

        WebElement userNameInput = driver.findElement(By.id("username"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);


        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();
    }

    public static void main(String[] args) throws InterruptedException {
        ChromeDriver driver = Util.getDriver(null);
        String url = "http://thome.ouchn.cn/";
        driver.get(url);
        Thread.sleep(10000);
     //   String userName = "xj_zhishu15";
        String userName = "xj_zhishu15";
        String pwd = "zsxy123456WY";


        Map<String, String> SUBJECT = Maps.newHashMap();
//        SUBJECT.put("04114", "会计学概论");
//        SUBJECT.put("04016", "人文英语4");
//        SUBJECT.put("04015", "人文英语3");
//        SUBJECT.put("04014", "人文英语2");
//        SUBJECT.put("04013", "人文英语1");
//        SUBJECT.put("04009", "商务英语1");
//        SUBJECT.put("04011", "商务英语3");
//        SUBJECT.put("00585", "国际经济法");
//        SUBJECT.put("04343", "外科护理学");
//        SUBJECT.put("02366", "外科护理学（本）");
//        SUBJECT.put("02367", "妇产科学与儿科护理学");
//        SUBJECT.put("02642", "学前儿童卫生与保健");
//        SUBJECT.put("02641", "学前教育原理");
//        SUBJECT.put("01640", "小企业管理");
//        SUBJECT.put("00490", "工程数学（本）");
//        SUBJECT.put("00493", "工程造价基础");
//        SUBJECT.put("02325", "市场营销学");
//        SUBJECT.put("02643", "幼儿园课程与活动设计");
//        SUBJECT.put("02644", "幼儿游戏与玩具");
//        SUBJECT.put("02652", "0-3岁婴幼儿的保育与教育");
//        SUBJECT.put("00038", "安装工程估价");
//        SUBJECT.put("00192", "成本管理");
//        SUBJECT.put("00236", "传感器与测试技术");
//        SUBJECT.put("00439", "钢结构（本）");
     //   SUBJECT.put("04114", "会计学概论");
        SUBJECT.put("00961", "经济法学");

        login(driver, userName, pwd);

        Thread.sleep(1000);
        Util.switchToFirst(driver);

        // d://newAnswer//
        List<String> names = Lists.newArrayList();
        for(File f1:new File("D:\\newAnswer").listFiles()){
            names.add(f1.getName());
        }

        for (String id : SUBJECT.keySet()) {
            if(names.contains(SUBJECT.get(id))){
                continue;
            }
            try {
                driver.get("http://thome.ouchn.cn/");
                Thread.sleep(2000);
                String subjectName = SUBJECT.get(id);
                InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-quiz.section");
                List<String> list1 = IOUtils.readLines(inputStream3);
                List<String> paths = new ArrayList<>();
                for (String str : list1) {
                    paths.add(str.split(",")[0]);
                }

                driver.findElement(By.id("txtclassname")).sendKeys(subjectName);
                driver.findElement(By.className("btnblue_m")).click();
                Thread.sleep(5000);


                for (WebElement we : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                        d -> d.findElements(By.tagName("tr")))) {
                    // 第一个TH是课程编号
                    if (Util.findByTagName(we, "td") == null) {
                        continue;
                    }
                    System.err.println("we.findElement(By.tagName(\"td\")).getText()):" + we.findElement(By.tagName("td")).getText());
                    if (!id.equals(we.findElement(By.tagName("td")).getText())) {
                        continue;
                    }
                    // 进入病理学与病理生理学
                    we.findElement(By.tagName("a")).click();
                    break;
                }
                Thread.sleep(5000);
                // ------------FIXME ----

                // 关闭其他页面，只留下当前课程页面
                Util.switchToFirst(driver);
                driver.close();
                Thread.sleep(2000);
                Util.switchToFirst(driver);
                List<Question> questions = Lists.newArrayList();
                // FIXME 如果标题相同就判断不出来了
                Set<String> titleSet = Sets.newHashSet();
                for (String urlTask : paths) {
                    driver.get(urlTask);
                    Thread.sleep(5000);
                    // Util.switchToLast(driver);
                    driver.findElement(By.className("quizattemptcounts")).findElement(By.tagName("a")).click();
                    Thread.sleep(5000);
                    // 回顾试答
                    // reviewlink
                    List<WebElement> infoList = new WebDriverWait(driver, Duration.ofSeconds(90)).until((ExpectedCondition<List<WebElement>>)
                            d -> d.findElements(By.cssSelector("a[class='reviewlink']")));

                    boolean doubleGoBack = false;

                    int size = 0;
                    if(infoList.size()>10){
                        size = 4;
                    }else {
                        size = infoList.size();
                    }


                    //  for (int i = 0; i < infoList.size(); i++) {
                    for (int i = 0; i < size; i++) {
                        new WebDriverWait(driver, Duration.ofSeconds(90)).until((ExpectedCondition<List<WebElement>>)
                                d -> d.findElements(By.cssSelector("a[class='reviewlink']"))).get(i).click();
                        // FIXME TODO 获取题目信息

                        Thread.sleep(5000);
                        for (WebElement wa : driver.findElements(By.tagName("a"))) {
                            if ("在一页上显示所有试题".equals(wa.getText())) {
                                doubleGoBack = true;
                                wa.click();
                                Thread.sleep(5000);
                                break;
                            }

                        }


                        for (WebElement singleSubject : Util.getSinglePageQuestionList(driver)) {

                            if (null == singleSubject) {
                                continue;
                            }
                            String answerClass = singleSubject.getAttribute("class");
                            // informationitem  description description
                            if (Strings.isNullOrEmpty(answerClass)) {
                                continue;
                            }
                            if (answerClass.contains("description") || answerClass.contains("informationitem")) {
                                continue;
                            }
                            Question question = new Question();
                            question.setAnalyze("无");
                            question.setDifficult(1);
                            question.setGradeLevel(21);

                            String questionId = singleSubject.getAttribute("id");
                            // 这里的questionId是题目的ID
                            System.err.println("questionId:" + questionId);
                            WebElement contentElement = singleSubject.findElement(By.className("content"));

                            WebElement hiddenElement = singleSubject.
                                    findElement(By.cssSelector("input[type='hidden']"));
                            // 题干
                            String name = hiddenElement.getAttribute("name");
                            System.err.println("name:" + name);
                            // qtext
                            // 题目标题
                            String title = Util.getTitle(contentElement);
                            question.setTitle(title);
                            // FIXME
                            if (titleSet.contains(title)) {
                                continue;
                            }
                            // 题目提示 tip prompt
                            WebElement promptElement = Util.findByClassName(contentElement, "prompt");
                            if (null != promptElement) {
                                System.err.println("promptElement:" + promptElement.getText());
                            }

                            WebElement answerElement = Util.findByClassName(contentElement, "answer");
                            String labelType = "";
                            List<Item> items = Lists.newArrayList();
                            items.clear();
                            if (null != answerElement) {
                                // 找到每一个选项
                                // 针对多选和单选和判断题
                                for (WebElement singleAnswerElement : answerElement.
                                        findElements(By.cssSelector("div[class^='r0'],div[class^='r1']"))) {
                                    // 答案的序号 判断题没有序号 多选和单选有序号
                                    String answerNumber = "";
                                    WebElement numberElement = Util.findByClassName(singleAnswerElement, "answernumber");
                                    if (numberElement != null) {
                                        answerNumber = numberElement.getText();
                                    }
                                    // 每个答案的文本 p标签 =单选和多选 label标签=判断题
                                    String answerContent = Util.getAnswer(singleAnswerElement);
                                    // 找到单选框或复选框
                                    WebElement checkboxElement = singleAnswerElement.
                                            findElement(By.cssSelector("input[type='checkbox'],input[type='radio']"));
                                    labelType = checkboxElement.getAttribute("type");
                                    // 这里的ID是每个选项的ID
                                    // answerContent是每个选项的内容
                                    Item item = new Item();
                                    item.setPrefix(answerNumber);
                                    item.setContent(answerContent);
                                    if (Strings.isNullOrEmpty(answerContent)) {
                                        item.setPrefix(answerContent);
                                    }
                                    items.add(item);
                                }
                            }


                            // 获取正确答案
                            WebElement rightAnswer = Util.findByClassName(singleSubject, "rightanswer");
                            if (rightAnswer != null) {
                                //     String[] correctArray = new String[]{rightAnswer.getText()};
                                String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                                question.setCorrectArray(correctArray);
                            }
                            if (question.getCorrectArray() == null) {
                                rightAnswer = Util.findByClassName(singleSubject, "generalfeedback");
                                if (rightAnswer != null) {
                                    //  String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                                    String[] correctArray = new String[]{rightAnswer.getText()};
                                    question.setCorrectArray(correctArray);
                                }
                            }

                            question.setItems(items);
                            titleSet.add(question.getTitle());

                            answerClass = singleSubject.getAttribute("class");
                            // 简单题que essay manualgraded notyetanswered
                            if (answerClass.contains("essay")) {
                                // 等于选项的ID
                                question.setQuestionType(5);
                                question.setQuestionTypeDesc("简答题");
                                question.setCorrect("简单题");
                                questions.add(question);
                            }
                            // 判断题 que truefalse manualgraded notyetanswered  que truefalse deferredfeedback notyetanswered
                            if (answerClass.contains("truefalse")) {
                                question.setQuestionType(3);
                                question.setQuestionTypeDesc("判断题");
                                questions.add(question);
                            }
                            // 填空题 que shortanswer deferredfeedback notyetanswered
                            if (answerClass.contains("shortanswer") || answerClass.contains("multianswer")) {
                                // 等于选项的ID
                                question.setQuestionType(4);
                                question.setQuestionTypeDesc("填空题");
                                questions.add(question);
                            }
                            // 多选|单选：que multichoice deferredfeedback notyetanswered
                            if (answerClass.contains("multichoice")) {
                                if ("radio".equals(labelType)) {
                                    question.setQuestionType(1);
                                    question.setQuestionTypeDesc("单选题");
                                    questions.add(question);
                                }
                                if ("checkbox".equals(labelType)) {
                                    question.setQuestionType(2);
                                    question.setQuestionTypeDesc("多选题");
                                    questions.add(question);
                                }
                            }

                        }
                        Thread.sleep(5000);
                        driver.navigate().back();
                        Thread.sleep(2000);
                        if (doubleGoBack) {
                            driver.navigate().back();
                            Thread.sleep(2000);
                        }

                    }
                    Thread.sleep(2000);
                    //  driver.close();
                    Util.switchToLast(driver);
                    Thread.sleep(2000);

                }

                Collections.sort(questions);
                List<Map<String, Object>> answers = new ArrayList<>();
                for (Question question : questions) {

                    String title = question.getTitle();
                    title = Util.dealContent(title);
                    Map<String, Object> answerMap = new HashMap<>();
                    answerMap.put("questionType", question.getQuestionType());
                    answerMap.put("answerType", "click");

                    answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
                    answerMap.put("questionTitle", title);
                    answerMap.put("questionCode", MD5Utils.encode(subjectName + title));
                    answerMap.put("items", question.getItems());
                    answerMap.put("answers", question.getCorrectArray());

                    answers.add(answerMap);
                }

                FileUtils.write(new File("d://newAnswer//" + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        Thread.sleep(12000);
        driver.quit();
    }
}
